import { _decorator, Component, Node, sys, Vec2 } from 'cc';
import { MonsterOrigin, MonsterState } from './MonsterOrigin';
import { ConfigKey, EventName, PopView, monster_Refresh_config, monster_base_config, skin_config } from '../../manager/AppControll';
import { GameData, PhaseTransitionType } from '../../system/GameData';
import EvtManger from '../../tools/EvtManger';
import { CoinDropType } from '../Drop';
import { DataHelper } from '../../system/DataHelper';
import { PopManager } from '../../manager/PopManager';
import { GetSkinDebris } from '../../pop/GetSkinDebris';
import { SoundManager } from '../../manager/SoundManger';
import { Tools } from '../../tools/Tools';
import { MAnimation } from '../component/MAnimation';
import { Move } from '../component/Move';
import { MonsterManager } from './MonsterManager';
import { LevelMonsterManager } from '../levelModel/LevelMonsterManager';
import { FightControl, GameModel } from '../FightControl';
import { Hp } from '../component/Hp';
const { ccclass, property } = _decorator;

@ccclass('MonsterNormal')
export class MonsterNormal extends MonsterOrigin {
    protected onLoad(): void {
        super.onLoad();
    }

    InitMonster(config: monster_Refresh_config, base: monster_base_config) {
        super.InitMonster(config, base)
        this.scheduleOnce(() => {
            this.mBIsDeath = false;
        })
    }

    MoveFinish() {
        super.MoveFinish();
        if (FightControl.gamemodel == GameModel.levelModel) {
            EvtManger.do(EventName.levelModeMoveFinish, this.baseConfig.baseBlood);
        }
    }

    Die(): void {
        this.mState = MonsterState.die;
        this.node.getChildByName("lockTarget").active = false;
        this.node.getComponent(Move).Speed *= 0;
        this.node.getComponent(MAnimation).PlayDeath(() => {
            this.node.active = false;
            MonsterManager.normalMonsterPool.put(this.node);
        })
        this.scheduleOnce(() => {
            if (this.node.active) {
                this.node.active = false;
                MonsterManager.normalMonsterPool.put(this.node);
            }
        }, 1.5);
        SoundManager.Instance<SoundManager>().PlayEffect("death/" + this.baseConfig.deathAudio, Number.parseFloat(DataHelper.GetConfigByKey(ConfigKey.monsterVolume).value));
        if (DataHelper.GetMonsterRefreshConfigById(DataHelper.GetMonsterRefreshByAuto().stageID + 1)) {
            GameData.playerData.KillMonsters++;
        }
        let skinGold = DataHelper.GetSkinBuffGold();
        GameData.AddGold(this.baseConfig.baseGold * this.refreshConfig.dropGoldRatio * skinGold);
        GameData.AddHonor(this.baseConfig.baseHonor * this.refreshConfig.dropHonorRatio);

        if (FightControl.gamemodel == GameModel.normal) {
            Tools.RemoveElementByVaule(MonsterManager.ltMonster as [], this.node);
        } else if (FightControl.gamemodel == GameModel.levelModel) {
            Tools.RemoveElementByVaule(LevelMonsterManager.ltMonster as [], this.node);
        }

        EvtManger.do(EventName.monsterDeath, this.node);
        
        let dropType = null;
        if (GameData.giftGold == 1) {
            dropType = CoinDropType.one;
        } else if (GameData.giftGold == 3) {
            dropType = CoinDropType.three;
        }
        if (FightControl.gamemodel == GameModel.normal) this.DropSkin();
        if (FightControl.gamemodel == GameModel.levelModel) this.LevelDropSkin();

        EvtManger.do(EventName.dropCoins, this.node.position.clone(), dropType);
    }

    InitMoveComponent() {
        let ltTemp = this.refreshConfig.lineRoute;
        let id = this.refreshConfig.lineRoute[0];
        let move = this.node.getComponent(Move);
        if (ltTemp.length > 0) {
            id = ltTemp[Math.floor(Math.random() * (ltTemp.length))];
        }
        let lineConfig = DataHelper.GetMoveLineConfigById(id);
        let speed = this.baseConfig.baseSpeed * this.refreshConfig.speedRatio;
        //关卡模式 为多点路线 单独处理
        if (FightControl.gamemodel == GameModel.levelModel) {
            if (move) {
                if (FightControl.gamemodel == GameModel.levelModel) move.InitPointLt(lineConfig.levelLine, speed)
            } else {
                if (FightControl.gamemodel == GameModel.levelModel) this.node.addComponent(Move).InitPointLt(lineConfig.levelLine, speed);
            }
            return;
        }
        let startPoint = null;
        let endPoint = null;
        
        if (this.direction == 1) {
            startPoint = new Vec2(lineConfig.leftPosition[0], lineConfig.leftPosition[1]);
            endPoint = new Vec2(lineConfig.rightPosition[0], lineConfig.rightPosition[1]);
        } else {
            startPoint = new Vec2(lineConfig.rightPosition[0], lineConfig.rightPosition[1]);
            endPoint = new Vec2(lineConfig.leftPosition[0], lineConfig.leftPosition[1]);
        }
        this.startPoint = startPoint;
        this.endPoint = endPoint;
        if (move) {
            if (FightControl.gamemodel == GameModel.normal) move.InitPoint(startPoint, endPoint, speed);
        } else {
            if (FightControl.gamemodel == GameModel.normal) this.node.addComponent(Move).InitPoint(startPoint, endPoint, speed);

        }
    }

    DropSkin() {
        let config = DataHelper.GetSkin_config();
        let tempList: skin_config[] = [];//
        let resList = [];
        let result = null;
        for (const key in config) {
            if (Object.prototype.hasOwnProperty.call(config, key)) {
                const element: skin_config = config[key];
                let SkinFCount = DataHelper.GetSkinFragmentCountById(element.skinId);
                if (element.debrisDropStage && element.dropType == 1) {
                    let level = DataHelper.GetMonsterRefreshConfig().stageID - 10000;
                    if (element.debrisDropStage.indexOf(level) != -1 && GameData.playerData.skin.indexOf(element.skinId) == -1) {
                        if (SkinFCount >= element.unlockNeedDebris) continue;
                        tempList.push(element);
                    }
                }
            }
        }
        
        tempList.forEach((config) => {
            let randomNum: number = Math.random();
            let index = config.debrisDropStage.indexOf(DataHelper.GetMonsterRefreshConfig().stageID - 10000);
            if (randomNum <= config.debrisDropRate[index]) {
                resList.push(randomNum);
            }
        })


        if (resList.length >= 1) {
            result = tempList[Math.floor(Math.random() * tempList.length)];
        }
        if (result) {
            PopManager.Instance<PopManager>().ShowPop(PopView.getSkinDebris, (node) => {
                node.getComponent(GetSkinDebris).InitSkinDebris(result);
            });
        }
    }

    LevelDropSkin() {
        let configs = DataHelper.GetSkin_config();
        let config: skin_config = null;
        let result = false;
        for (const key in configs) {
            if (Object.prototype.hasOwnProperty.call(configs, key)) {
                const element: skin_config = configs[key];
                let SkinFCount = DataHelper.GetSkinFragmentCountById(element.skinId)
                if (element.dropType == 2 && GameData.playerData.skin.indexOf(element.skinId) == -1) { //dropType为2时  为关卡掉落
                    if (SkinFCount >= element.unlockNeedDebris) continue;
                    config = element;
                    break;
                }
            }
        }

        if (!config) return;
        let randomNum: number = Math.random();
        let index = FightControl.nCurLevel;
        if (randomNum <= config.debrisDropRate[index]) {
            result = true;
        }

        if (result) {
            PopManager.Instance<PopManager>().ShowPop(PopView.getSkinDebris, (node) => {
                node.getComponent(GetSkinDebris).InitSkinDebris(config);
            });
        }

    }

    protected update(dt: number): void {
        super.update(dt);
    }

    unuse() {
        this.mCurTime = 0;
        this.mBIsDeath = true;
        if (this.node.getComponent(Hp)) this.BeNormal();
        if (this.node.getComponent(MAnimation)) this.node.getComponent(MAnimation).StopAll();
        this.unscheduleAllCallbacks();
    }

    reuse() {

    }

    protected onDestroy(): void {
        super.onDestroy();
    }
}

declare let wx: any;



